﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier_Interface;
using Cashier_Service;
using Cashier.utils;
using Cashier_Model;
using Cashier.pos;
using Cashier_Utils;
using System.Collections;

namespace Cashier.shipment
{
    public partial class SalesReturnForm : Form, IGoodsNorm
    {
        private IReloadData iReloadData;
        private MainForm mainform;
        private static SalesReturnForm salesReturnForm;
        private BillShipmentService shipmentService;
        private BillShipmentGoodsService shipmentGoodsService;
        private BillReshipmentService reshipmentService;
        private BillReshipmentGoodsService reshipmentGoodsService;
        private DataTable goodsTable;
        private DataRow goodsDataRow;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="iReloadData"></param>
        private SalesReturnForm(MainForm mainform, IReloadData iReloadData)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.iReloadData = iReloadData;
            this.shipmentService = new BillShipmentService();
            this.shipmentGoodsService = new BillShipmentGoodsService();
            this.reshipmentService = new BillReshipmentService();
            this.reshipmentGoodsService = new BillReshipmentGoodsService();

            Button[] buttons = { button_save };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            this.GenerateDataGridViewColumns();
        }

        /// <summary>
        /// 返回窗体实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="iReloadData"></param>
        /// <returns></returns>
        public static SalesReturnForm GetSalesReturnForm(MainForm mainform, IReloadData iReloadData)
        {
            if (salesReturnForm == null)
                salesReturnForm = new SalesReturnForm(mainform, iReloadData);
            return salesReturnForm;
        }

        /// <summary>
        /// 初始化DataGridView列
        /// </summary>
        protected void GenerateDataGridViewColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("barcode", "商品条码", true, 9, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_name", "商品名称", true, 16, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("category_name", "商品分类", true, 7, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_norm", "商品规格", true, 7, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_sale", "商品单价", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("discount", "折扣率", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_disc", "出货单价", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("numbers", "出货数量", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("total", "合计", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("paid", "已付款", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("debt", "欠款", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("renumbers", "退货数量", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("owe_total", "退货金额", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("note", "备注", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_cost", null, true, 0, null, null, false, false));
        }

        /// <summary>
        /// 商品条码键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_barcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 13)
            {
                try
                {
                    textbox_renumbers.Focus();
                    String barcode = this.textbox_barcode.Text.Trim();
                    String shipmentno = this.textbox_shipmentno.Text.Trim();
                    if (!String.IsNullOrEmpty(barcode))
                    {
                        goodsTable = shipmentGoodsService.GetBillShipmentGoodsTable(0, 0, mainform.Admin.EnterpriseNo, string.Empty, barcode, null, null, shipmentno, null, null, null, null, null, "id");
                        if (goodsTable != null)
                        {
                            if (goodsTable.Rows.Count > 1)
                            {
                                GoodsNormForm goodsNormForm = new GoodsNormForm(this, goodsTable, "goods_norm", "goods_id");
                                goodsNormForm.ShowDialog();
                            }
                            else if (goodsTable.Rows.Count == 1)
                            {
                                this.goodsDataRow = goodsTable.Rows[0];
                                this.InitialGoodsData();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogsUtil.Record(ex);
                }
            }
        }

        #region IGoodsNorm 成员

        void IGoodsNorm.SelectGoodsNorm(object param)
        {
            try
            {
                if (param != null)
                {
                    DataRow row = (DataRow)param;
                    this.goodsDataRow = row;
                    this.InitialGoodsData();                   
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion

        /// <summary>
        /// 初始化商品数据
        /// </summary>
        /// <param name="row"></param>
        protected void InitialGoodsData()
        {
            if (this.goodsDataRow != null)
            {
                DataRow row = this.goodsDataRow;
                label_goodsName.Text = row["goods_name"].ToString();
                label_categoryname.Text = row["category_name"].ToString();
                label_goodsNorm.Text = row["goods_norm"].ToString();
                label_priceSale.Text = ((decimal)row["price_sale"]).ToString("f2");
                label_discount.Text = row["discount"].ToString();
                label_priceDisc.Text = ((decimal)row["price_disc"]).ToString("f2");
                label_goodsNumber.Text = row["numbers"].ToString();
                label_goodsAmount.Text = ((decimal)row["total"]).ToString("f2");
                label_paid.Text = ((decimal)row["paid"]).ToString("f2");
                label_debt.Text = ((decimal)row["debt"]).ToString("f2");

                textbox_renumbers.Text = label_goodsNumber.Text;
                textbox_oweTotal.Text = label_goodsAmount.Text;
            }
            else
            {
                textbox_barcode.Text = String.Empty;
                label_goodsName.Text = String.Empty;
                label_categoryname.Text = String.Empty;
                label_goodsNorm.Text = String.Empty;
                label_priceSale.Text = "0.00";
                label_discount.Text = "0.0";
                label_priceDisc.Text = "0.00";
                label_goodsNumber.Text = "0";
                label_goodsAmount.Text = "0.00";
                label_paid.Text = "0.00";
                label_debt.Text = "0.00";

                textbox_renumbers.Text = String.Empty;
                textbox_oweTotal.Text = String.Empty;
                textbox_goodsnote.Text = String.Empty;
                textbox_barcode.Focus();
            }
        }

        /// <summary>
        /// 添加DataGridView行
        /// </summary>
        protected void AddDataGridViewRow()
        {
            if (this.goodsDataRow != null)
            {
                bool isExist = false;
                long goodsId = (long)goodsDataRow["goods_id"];
                int numbers = Int32.Parse(goodsDataRow["numbers"].ToString());
                decimal paid = (decimal)goodsDataRow["paid"];
                decimal debt = (decimal)goodsDataRow["debt"];

                if (debt > 0)
                {
                    MessageBox.Show("请先付完欠款后再办理退货手续！");
                    return;
                }
                String renumbers = textbox_renumbers.Text.Trim();
                if (String.IsNullOrEmpty(renumbers))
                {
                    MessageBox.Show("请输入退货数量！");
                    return;
                }
                if (Int32.Parse(renumbers) > numbers)
                {
                    MessageBox.Show("退货数量不得高于购买数量！");
                    return;
                }
                String goodsAmount = textbox_oweTotal.Text.Trim();
                if (Decimal.Parse(goodsAmount) > paid)
                {
                    MessageBox.Show("退款不得高于商品付款金额！");
                    return;
                }
                long existCount = this.reshipmentGoodsService.ExistBillReshipmentGoods(this.goodsDataRow["shipment_no"].ToString(),
                    this.goodsDataRow["barcode"].ToString(), this.goodsDataRow["goods_norm"].ToString());
                if (existCount > 0)
                {
                    MessageBox.Show("此商品已经办理过退货手续！");
                    this.goodsDataRow = null;
                    this.InitialGoodsData();
                    return;
                }

                if (dataGridView1.Rows.Count > 0)
                {
                    foreach (DataGridViewRow dgvRow in dataGridView1.Rows)
                    {
                        if ((long)dgvRow.Cells["goods_id"].Value == goodsId)
                        {
                            isExist = true;
                            break;
                        }
                    }
                }
                if (!isExist)
                {
                    int rowIndex = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[rowIndex].Cells["goods_id"].Value = this.goodsDataRow["goods_id"];
                    this.dataGridView1.Rows[rowIndex].Cells["barcode"].Value = this.goodsDataRow["barcode"];
                    this.dataGridView1.Rows[rowIndex].Cells["goods_name"].Value = this.goodsDataRow["goods_name"];
                    this.dataGridView1.Rows[rowIndex].Cells["category_name"].Value = this.goodsDataRow["category_name"];
                    this.dataGridView1.Rows[rowIndex].Cells["goods_norm"].Value = this.goodsDataRow["goods_norm"];
                    this.dataGridView1.Rows[rowIndex].Cells["price_cost"].Value = this.goodsDataRow["price_cost"];
                    this.dataGridView1.Rows[rowIndex].Cells["price_sale"].Value = this.goodsDataRow["price_sale"];
                    this.dataGridView1.Rows[rowIndex].Cells["discount"].Value = this.goodsDataRow["discount"];
                    this.dataGridView1.Rows[rowIndex].Cells["price_disc"].Value = this.goodsDataRow["price_disc"];
                    this.dataGridView1.Rows[rowIndex].Cells["numbers"].Value = this.goodsDataRow["numbers"];
                    this.dataGridView1.Rows[rowIndex].Cells["total"].Value = this.goodsDataRow["total"];
                    this.dataGridView1.Rows[rowIndex].Cells["paid"].Value = this.goodsDataRow["paid"];
                    this.dataGridView1.Rows[rowIndex].Cells["debt"].Value = this.goodsDataRow["debt"];
                    this.dataGridView1.Rows[rowIndex].Cells["renumbers"].Value = Int32.Parse(renumbers);
                    this.dataGridView1.Rows[rowIndex].Cells["owe_total"].Value = Decimal.Parse(goodsAmount);
                    this.dataGridView1.Rows[rowIndex].Cells["note"].Value = textbox_goodsnote.Text.Trim();

                    this.dataGridView1.Rows[rowIndex].Selected = true;
                    this.goodsDataRow = null;
                    this.InitialGoodsData();

                    this.ReshipmentAccount();
                }
                else
                    MessageBox.Show("商品已存在！");
            }
        }

        /// <summary>
        /// 退货结帐
        /// </summary>
        public void ReshipmentAccount()
        {
            try
            {
                if (this.dataGridView1.Rows.Count > 0)
                {
                    int returnNumbers = 0;
                    decimal returnGoodsAmount = 0M;
                    decimal reshipmentTotal = 0M;
                    decimal reshipmentPaid = 0M;
                    //decimal reshipmentOwe = 0M;
                    foreach (DataGridViewRow lopRow in this.dataGridView1.Rows)
                    {
                        returnNumbers += (int)lopRow.Cells["renumbers"].Value;
                        returnGoodsAmount += (decimal)lopRow.Cells["price_disc"].Value * (int)lopRow.Cells["renumbers"].Value;
                        reshipmentTotal += (decimal)lopRow.Cells["owe_total"].Value;
                    }
                    reshipmentPaid = reshipmentTotal;

                    label_numbers.Text = returnNumbers.ToString();
                    label_goodsTotal.Text = returnGoodsAmount.ToString("f2");
                    textbox_reshipmentTotal.Text = reshipmentTotal.ToString("f2");
                    textbox_reshipmentPaid.Text = reshipmentTotal.ToString("f2");
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 保存退货单
        /// </summary>
        public void SaveReshipemt()
        {
            try
            {
                decimal goodsTotal = Decimal.Parse(label_goodsTotal.Text);
                decimal reshipmentTotal = Decimal.Parse(textbox_reshipmentTotal.Text.Trim());
                decimal reshipmentPaid = Decimal.Parse(textbox_reshipmentPaid.Text.Trim());
                decimal reshipmentOwe = Decimal.Parse(textbox_reshipmentOwe.Text.Trim());
                if (reshipmentTotal > goodsTotal)
                {
                    MessageBox.Show("应退金额不得高于商品金额！");
                    return;
                }
                if (reshipmentPaid > reshipmentTotal)
                {
                    MessageBox.Show("实退金额不得高于应退金额！");
                    return;
                }
                if ((reshipmentPaid + reshipmentOwe) > reshipmentTotal)
                {
                    MessageBox.Show("欠退金额与实退金额之和不得高于应退金额！");
                    return;
                }
                if (dataGridView1.Rows.Count < 1)
                {
                    MessageBox.Show("无退货商品！");
                    return;
                }

                BillReshipment billReshipment = new BillReshipment();
                billReshipment.EnterpriseNo = mainform.Admin.EnterpriseNo;
                billReshipment.StoreNo = mainform.Admin.StoreNo;
                billReshipment.Reshipmentno = ToolsUtil.GenerateReshipmentNO();
                billReshipment.Shipmentno = textbox_shipmentno.Text.Trim();
                billReshipment.Memberno = label_memberno.Text;
                billReshipment.Numbers = Int32.Parse(label_numbers.Text);
                billReshipment.GoodsTotal = goodsTotal;
                billReshipment.ReshipmentTotal = reshipmentTotal;
                billReshipment.ReshipmentPaid = reshipmentPaid;
                billReshipment.ReshipmentOwe = reshipmentOwe;
                billReshipment.ReshipmentDate = DateTime.Now;
                billReshipment.Note = textbox_note.Text.Trim();
                billReshipment.AdminUsername = mainform.Admin.Username;
                billReshipment.AdminName = mainform.Admin.Name;
                billReshipment.Createtime = DateTime.Now;
                ArrayList list = new ArrayList();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    BillReshipmentGoods reshipmentGoods = new BillReshipmentGoods();
                    reshipmentGoods.EnterpriseNo = billReshipment.EnterpriseNo;
                    reshipmentGoods.StoreNo = billReshipment.StoreNo;
                    reshipmentGoods.Reshipmentno = billReshipment.Reshipmentno;
                    reshipmentGoods.Shipmentno = billReshipment.Shipmentno;
                    reshipmentGoods.Barcode = row.Cells["barcode"].Value.ToString();
                    reshipmentGoods.CategoryName = row.Cells["category_name"].Value.ToString();
                    reshipmentGoods.GoodsName = row.Cells["goods_name"].Value.ToString();
                    reshipmentGoods.GoodsNorm = row.Cells["goods_norm"].Value.ToString();
                    reshipmentGoods.PriceCost = (decimal)row.Cells["price_cost"].Value;
                    reshipmentGoods.PriceSale = (decimal)row.Cells["price_sale"].Value;
                    reshipmentGoods.Discount = (decimal)row.Cells["discount"].Value;
                    reshipmentGoods.PriceDisc = (decimal)row.Cells["price_disc"].Value;
                    reshipmentGoods.Numbers = Int32.Parse(row.Cells["numbers"].Value.ToString());
                    reshipmentGoods.GoodsTotal = (decimal)row.Cells["total"].Value;
                    reshipmentGoods.Renumbers = Int32.Parse(row.Cells["renumbers"].Value.ToString());
                    reshipmentGoods.OweTotal = (decimal)row.Cells["owe_total"].Value;
                    reshipmentGoods.Note = row.Cells["note"].Value.ToString();
                    reshipmentGoods.AdminUsername = billReshipment.AdminUsername;
                    reshipmentGoods.AdminName = billReshipment.AdminName;
                    reshipmentGoods.Createtime = DateTime.Now;
                    list.Add(reshipmentGoods);
                }
                long id = reshipmentService.InsertBillReshipment(billReshipment, list);
                if (id > 0)
                {
                    iReloadData.ReloadDataGridViewData(null);
                    DialogResult result = MessageBox.Show("促存退货单成功，继续退货处理？", "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        textbox_shipmentno.Focus();
                        textbox_shipmentno.Text = String.Empty;
                        label_memberno.Text = String.Empty;
                        label_numbers.Text = "0";
                        label_goodsTotal.Text = "0.00";
                        textbox_reshipmentTotal.Text = "0.00";
                        textbox_reshipmentPaid.Text = "0.00";
                        textbox_reshipmentOwe.Text = "0.00";
                        this.dataGridView1.Rows.Clear();
                    }
                    else
                        this.Close();
                }
                else
                    MessageBox.Show("促存退货单失败！");
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 重新扫入退货商品
        /// </summary>
        protected void RepeatAddGoods()
        {
            this.goodsDataRow = null;
            this.InitialGoodsData();
            textbox_barcode.Focus();
        }

        /// <summary>
        /// 删除退货商品
        /// </summary>
        protected void DeleteReshipmentGoods()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                DialogResult result = MessageBox.Show("确定要删除选中商品吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    int rowIndex = this.dataGridView1.SelectedRows[0].Index;
                    this.dataGridView1.Rows.RemoveAt(rowIndex);
                }
            }
        }

        #region 窗体控件事件

        /// <summary>
        /// 出货单号按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_shipmentno_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                String shipmentno = textbox_shipmentno.Text.Trim();
                if (!String.IsNullOrEmpty(shipmentno))
                {
                    BillShipment billShipment = shipmentService.GetBillShipment(0L, shipmentno);
                    if (billShipment != null && billShipment.Id > 0)
                    {
                        label_memberno.Text = billShipment.Memberno;

                        this.textbox_barcode.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 添加退货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_addGoods_Click(object sender, EventArgs e)
        {
            this.AddDataGridViewRow();
        }

        /// <summary>
        /// 保存退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_save_Click(object sender, EventArgs e)
        {
            this.SaveReshipemt();
        }

        /// <summary>
        /// 重扫退货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_repeat_Click(object sender, EventArgs e)
        {
            this.RepeatAddGoods();
        }

        /// <summary>
        /// 删除退货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_delete_Click(object sender, EventArgs e)
        {
            this.DeleteReshipmentGoods();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SalesReturnForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            salesReturnForm = null;
        }

        #endregion

        #region 重写方法

        /// <summary>
        /// 重写键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.Add:
                    this.AddDataGridViewRow();
                    b = true;
                    break;
                case Keys.Oemplus:
                    this.AddDataGridViewRow();
                    b = true;
                    break;
                case Keys.F5:
                    this.SaveReshipemt();
                    break;
                case Keys.F6:
                    this.RepeatAddGoods();
                    break;
                case Keys.Delete:
                    this.DeleteReshipmentGoods();
                    break;
                case Keys.Escape:
                    this.Close();
                    break;
            }
            return b;
        }

        #endregion
    }
}
